package club.dmyang.common.util;

import club.dmyang.common.constants.Constants;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Created by brss on 2018/7/15.
 */
public class QiNiuUploadUtil {

    public static String uploadInputStream(InputStream inputStream){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        String hashFileName = "";
        try {
            Auth auth = Auth.create(Constants.QINIU_ACCESS_KEY, Constants.QINIU_SECRET_KEY);
            String uploadToken = auth.uploadToken(Constants.QINIU_HEAD_IMG_BUCKET_NAME, key);
                Response response = uploadManager.put(inputStream, key, uploadToken, null, null);
                //System.out.println(response);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                hashFileName = putRet.key;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hashFileName;
    }
}
